package com.sheepone.util.io;

import com.alibaba.fastjson2.JSON;
import com.sheepone.util.enums.FileExtension;
import com.sheepone.util.exception.ExceptionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author Miss.杨
 * @description
 * @since 2024/3/31 - 13:05
 */
public class FileUtil {
    private static final Logger logger = LoggerFactory.getLogger(new Object() {
    }.getClass().getEnclosingClass());

    private FileUtil() {

    }

    /**
     * 获取文件名
     *
     * @param fileAbsolutePath 文件的绝对路径
     * @return 文件名
     */
    public static String getFileName(String fileAbsolutePath) {
        Path path = Paths.get(fileAbsolutePath);
        String fileName = path.getFileName().toString();

        // 去掉扩展名
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex != -1) {
            fileName = fileName.substring(0, dotIndex);
        }
        return fileName;
    }

    /**
     * 将对象以JSON格式写入文件
     *
     * @param object        对象
     * @param directoryPath 目录
     * @param fileName      文件名
     * @param fileType      文件类型（拓展名）
     */
    public static void writeJson(Object object, String directoryPath, String fileName, String fileType) {
        writeJson(object, directoryPath + File.separator + fileName + "." + fileType);
    }

    /**
     * 将对象以JSON格式写入文件，默认拓展名为“json”
     *
     * @param object        对象
     * @param directoryPath 目录
     * @param fileName      文件名
     */
    public static void writeJson(Object object, String directoryPath, String fileName) {
        writeJson(object, directoryPath, fileName, "json");
    }

    /**
     * 将对象以JSON格式写入文件
     *
     * @param object           对象
     * @param fileAbsolutePath 文件绝对路径
     */
    public static void writeJson(Object object, String fileAbsolutePath) {
        writeJson(JSON.toJSONString(object), fileAbsolutePath);
    }

    /**
     * 将json字符串写入文件，如果该文件已存在，则会清除原有内容并写入新的JSON数据
     *
     * @param json             json字符串
     * @param fileAbsolutePath 文件绝对路径
     */
    public static void writeJson(String json, String fileAbsolutePath) {
        File file = new File(fileAbsolutePath);
        ExceptionUtil.throwIllegalArgumentExceptionIf(!file.isAbsolute(), "File path is not absolute: " + fileAbsolutePath);
        File parentDir = file.getParentFile();
        ExceptionUtil.throwIOOperateExceptionIf(!parentDir.exists() && !parentDir.mkdirs(), "Failed to create the parent directory for file: " + parentDir.getAbsolutePath());

        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) {
                writer.write(json);
                writer.flush();
            }
        } catch (IOException e) {
            ExceptionUtil.throwException(e, "Failed to write JSON to file: " + fileAbsolutePath);
        }
    }

    public static String readJson(String directoryPath, String fileName) {
        return readJson(directoryPath, fileName, FileExtension.JSON.name());
    }

    public static String readJson(String directoryPath, String fileName, FileExtension fileType) {
        return readJson(directoryPath + File.separator + fileName + "." + fileType.name());
    }

    public static String readJson(String directoryPath, String fileName, String fileType) {
        return readJson(directoryPath + File.separator + fileName + "." + fileType);
    }

    public static String readJson(String fileAbsolutePath) {
        File file = new File(fileAbsolutePath);
        if (!file.exists() || !file.isFile()) {
            logger.error("The specified file does not exist or is not accessible: " + fileAbsolutePath);
            return null;
        }
        StringBuilder contentBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileAbsolutePath), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                contentBuilder.append(line);
            }
            return contentBuilder.toString();
        } catch (IOException e) {
            logger.error("Failed to read JSON from file: " + fileAbsolutePath);
            return null;
        }
    }

    public static boolean deleteFile(String directoryPath, String fileName, FileExtension fileType) {
        return deleteFile(directoryPath + File.separator + fileName + "." + fileType.name());
    }

    public static boolean deleteFile(String fileAbsolutePath, FileExtension fileType) {
        if (fileAbsolutePath == null) {
            return true;
        }
        if (!fileAbsolutePath.endsWith("." + fileType.name())) {
            return deleteFile(fileAbsolutePath + "." + fileType.name());
        }
        File file = new File(fileAbsolutePath);
        if (!file.exists() || !file.isFile()) {
            return true;
        }
        return file.delete();
    }

    public static boolean deleteFile(String fileAbsolutePath) {
        File file = new File(fileAbsolutePath);
        if (!file.exists() || !file.isFile()) {
            return true;
        }
        return file.delete();
    }
}
